package com.weijianhuawen.wjblog.web.utils;

/**
 * @version: java version 8
 * @Author: weijianhuawen
 * @description:
 * @date: 2025-03-08 14:51
 */
public class MarkdownEscapedUtil {
    public static String escaped(String originStr) {
        StringBuilder builder = new StringBuilder();
        int len = originStr.length();
        int i = 0;
        while (i < len - 1) {
            if (originStr.charAt(i) == '\\'
                    && (originStr.charAt(i + 1) == '(' || originStr.charAt(i + 1) == ')' || originStr.charAt(i + 1) == '[' || originStr.charAt(i + 1) == ']')) {
                builder.append("\\");
            } else if (originStr.charAt(i) == '\\' && originStr.charAt(i + 1) == '\\') {
                builder.append("\\\\\\");
                i++;
            } else if (originStr.charAt(i) == '`' && originStr.startsWith("```", i)) {
                builder.append("```");
                i += 3;
                while (i < len - 1 && !originStr.startsWith("```", i)) {
                    builder.append(originStr.charAt(i));
                    i++;
                }

                if (originStr.startsWith("```", i)) {
                    builder.append("```");
                    i += 3;
                }
                continue;
            }
            builder.append(originStr.charAt(i));
            i++;
        }
        builder.append(originStr.charAt(originStr.length() - 1));
        return builder.toString();
    }
}
